<?php
/**
 * Created by PhpStorm.
 * User: andrei
 * Date: Jun 27, 2012
 * Time: 2:34:57 PM
 * To change this template use File | Settings | File Templates.
 */
 
class Db_Products_Templates extends Common {
	protected static $tableName = TAB_TEMPLATES;
	protected static $dbFields = array(
        'id',
		't_size_id',
		't_name',
		't_module',
        'deleted'
	);
	/**
	 * @var Db_Products_Templates
	 */
	public $objectArray;

	public $id;
	public $t_size_id;
	public $t_name;
	public $t_module;
    public $deleted;

    function __construct($value=NULL, $fieldName=NULL) {
        parent::__construct($value, $fieldName);
    }

	/**
	 * @static
	 * @param $sizeId
	 * @param $allTemplates
	 * @param null $productId
	 * @return array
	 */
	public static function getTemplatesBySizeId($sizeId, $allTemplates, $productId = null) {
		$sqlAdd = '';
		if ($productId) {
			$productId = self::$DB->escapeValue($productId);
		}
		$themes = array();
		if(!$allTemplates) {
			$sqlAdd .= " INNER JOIN ". TAB_DESIGNS . " `d` ON `t`.`id` = `d`.`d_template_id` INNER JOIN ". TAB_THEMES. " `te` ON `d`.`d_theme_id` = `te`.`id` ";

            //get designs array [template id][theme id]
            $designs = array();
			$sqlDesignAdd = '';
			if ($productId) {
				$sqlDesignAdd = " INNER JOIN " . TAB_PRODUCT_THEME_PHOTOS . " pt ON d.d_theme_id = pt.pt_theme_id AND pt.pt_product_id = " . $productId;
			}
            $allDesigns = self::$DB->q("SELECT d.d_template_id, d.d_theme_id FROM ?f d {$sqlDesignAdd} WHERE d.deleted = 0", TAB_DESIGNS);

            while($data = $allDesigns->fetch_object()) {
                $designs[$data->d_template_id][$data->d_theme_id] = $data;
            }
			$sqlThemesAdd = '';
			if ($productId) {
				$sqlThemesAdd = " INNER JOIN " . TAB_PRODUCT_THEME_PHOTOS . " pt ON t.id = pt.pt_theme_id AND pt.pt_product_id = " . $productId ;
			}
			$themes = self::$DB->select("SELECT t.id FROM ?f t {$sqlThemesAdd} WHERE t.deleted = 0", TAB_THEMES);

			if(!empty($productId)) {
				$sqlAdd .= "INNER JOIN " . TAB_PRODUCT_THEME_PHOTOS . " AS `pt` ON `pt`.`pt_theme_id` = `te`.`id` AND `pt`.`pt_product_id` = {$productId}";
			}
		}

		$sql = "SELECT t.*, `t`.`id` as `template_id`, `li`.*,`li`.`id` as `li_id` FROM ?f AS `t`
				INNER JOIN ?f AS `li` ON `t`.`id` = `li`.`li_owner_id` AND `li`.`li_owned_by` = 'template'
				{$sqlAdd}
				WHERE `t`.`deleted` = 0 AND `li`.`deleted` = 0 AND `t`.`t_size_id` = ?d
				;";

		$templatesItems = self::$DB->q($sql, self::$tableName, TAB_LAYOUT_ITEMS, $sizeId);

		$dataConstruct = array();

		while($data = $templatesItems->fetch_object()) {
            $cutTemplate = false;
            if (!$allTemplates) {
                foreach ($themes as $theme) {
                    if(!isset($designs[$data->template_id][$theme['id']])) {
                        $cutTemplate = true;
                        break;
                    }
                }
            }
            if($cutTemplate) {
                continue;
            }
			$dataConstruct[$data->template_id]['t_name'] = $data->t_name;
			$dataConstruct[$data->template_id]['t_size_id'] = $data->t_size_id;
			$dataConstruct[$data->template_id]['items'][$data->li_id] = $data;
		}
		return $dataConstruct;

	}

	/**
	 * Function use for flash check associate designs themes vs products themes
	 *
	 * @static
	 * @param $sizeId
	 * @param $productId
	 * @return mixed
	 */
	public static function getValidTemplates($sizeId, $productId) {
		$sql = "SELECT * FROM ?f AS `t`
				INNER JOIN ?f AS `d` ON `d`.`d_template_id` = `t`.`id`
				LEFT JOIN ?f AS `pt` ON `d`.`d_theme_id` = `pt`.`pt_theme_id`
				WHERE pt_product_id = ? AND `t`.`t_size_id` = ?
				GROUP BY d_theme_id HAVING COUNT(d_theme_id) = (SELECT COUNT(*) FROM ?f WHERE pt_product_id = ?) ";

		return self::$DB->select($sql, self::$tableName, TAB_DESIGNS, TAB_PRODUCT_THEME_PHOTOS, $productId, $sizeId, TAB_PRODUCT_THEME_PHOTOS, $productId);
	}



	/**
	 * @static
	 * @param $limit
	 * @param string $searchSql
	 * @param string $orderBy
	 * @return mixed
	 */
	public static function getAllTemplates($limit, $searchSql = '', $orderBy = '') {
        if (empty($searchSql)) {
            $searchSql = '1=1';
			$joinSearch = '';
        } else {
			$joinSearch = " LEFT JOIN " . TAB_TRANSLATIONS . " tr ON tr.t_module = t.t_module AND tr.t_key = t.t_name AND tr.t_lang_id = " . conf('COUNTRY_LANG_ID') ;
			$joinSearch .= " LEFT JOIN " . TAB_TRANSLATIONS . " tr2 ON tr2.t_module = s.s_module AND tr2.t_key = s.s_name AND tr2.t_lang_id = " . conf('COUNTRY_LANG_ID') ;

			$searchSql .= " OR (`tr`.`t_content` LIKE " . self::$DB->escapeValue('%' . str_replace('%', "\\%", post('sSearch')) . '%') . ")";
			$searchSql .= " OR (`tr2`.`t_content` LIKE " . self::$DB->escapeValue('%' . str_replace('%', "\\%", post('sSearch')) . '%') . ")";
		}

		if (empty($orderBy)) {
			$orderBy = ' ORDER BY `t`.`id` ASC ';
		}

        $sql = "SELECT *, `t`.`id` AS `t_id`, `d`.`id` AS `d_id` FROM ?f AS `t`
                INNER JOIN ?f AS `s` ON `s`.`id` = `t`.`t_size_id` AND `s`.`deleted` = 0 AND `t`.`deleted` = 0
                LEFT JOIN ?f AS `d` ON `t`.`id` = `d`.`d_template_id` AND `d`.`deleted` = 0
                {$joinSearch}
                WHERE t.deleted = 0 AND {$searchSql} GROUP BY `t`.`id` {$orderBy} {$limit};";

        return self::$DB->select($sql, self::$tableName, TAB_SIZES, TAB_DESIGNS);
    }

	public static function getTotalTemplates($sqlCondition = '1=1') {
		if (empty($sqlCondition)) {
			$sqlCondition = '1=1';
			$joinSearch = '';
		} else {
			$joinSearch = " LEFT JOIN " . TAB_TRANSLATIONS . " tr ON tr.t_module = t.t_module AND tr.t_key = t.t_name AND tr.t_lang_id = " . conf('COUNTRY_LANG_ID') ;
			$sqlCondition .= " OR (`tr`.`t_content` LIKE " . self::$DB->escapeValue('%' . str_replace('%', "\\%", post('sSearch')) . '%') . ")";
		}
		$sql = "SELECT COUNT(*) FROM ?f AS `t`
                INNER JOIN ?f AS `s` ON `s`.`id` = `t`.`t_size_id` AND `s`.`deleted` = 0 AND `t`.`deleted` = 0
                {$joinSearch}
                WHERE {$sqlCondition} ;";
		return self::$DB->selectCell($sql, self::$tableName, TAB_SIZES);
	}


    public static function getTemplateById($templateId) {
        if(!$templateId) {
            return false;
        }
        $sql = 'SELECT *, `t`.`id` AS `t_id` FROM ?f AS `t`
                INNER JOIN ?f AS `s` ON `s`.`id` = `t`.`t_size_id`
                WHERE `t`.`id` = ? AND `t`.`deleted` = 0 AND `s`.`deleted` = 0;';

        return self::$DB->selectRow($sql, self::$tableName, TAB_SIZES, $templateId);
    }


}